<template>
  <el-container class="friends-container">
    <!-- 左侧好友列表 -->
    <el-aside width="300px" class="friends-sidebar">
      <!-- 搜索区域 -->
      <div class="search-section">
        <el-input
          v-model="searchValue"
          placeholder="搜索好友..."
          :prefix-icon="Search"
          clearable
        />
      </div>

      <!-- 好友列表 -->
      <el-scrollbar class="friends-scrollbar">
        <!-- 加载状态 -->
        <div v-if="loading" class="loading-section">
          <el-skeleton :rows="8" animated />
        </div>

        <!-- 空状态 -->
        <el-empty 
          v-else-if="friends.length === 0" 
          description="暂无好友"
          :image-size="100"
        >
          <template #image>
            <el-icon :size="60" color="#C0C4CC"><UserFilled /></el-icon>
          </template>
          <el-button type="primary" @click="addFriend">添加好友</el-button>
        </el-empty>

        <!-- 好友分组列表 -->
        <div v-else class="friends-list">
          <div
            v-for="group in filteredFriends"
            :key="group.letter"
            class="friend-group">
            
            <!-- 分组标题 -->
            <div class="group-header">
              <el-text class="group-title" size="small" type="info">
                {{ group.letter }} ({{ group.users.length }})
              </el-text>
            </div>

            <!-- 好友项 -->
            <div class="group-content">
              <div
                v-for="user in group.users"
                :key="user.id"
                :class="{ active: user.id === selectedUserId }"
                @click="handleClickUser(user.id)"
                class="friend-item">
                
                <el-avatar :size="40" :src="'/images/face/' + user.icon" class="friend-avatar">
                  <img :src="'/images/face/' + user.icon" />
                </el-avatar>
                
                <div class="friend-info">
                  <el-text class="friend-name" truncated>{{ user.nickname }}</el-text>
                  <el-text class="friend-summary" size="small" type="info" truncated>
                    {{ user.summary || '这个人很懒，什么都没留下' }}
                  </el-text>
                </div>

                <div class="friend-status">
                  <el-tag v-if="user.robot" size="small" type="success" effect="plain">AI</el-tag>
                  <el-icon v-else color="#67C23A"><CircleCheckFilled /></el-icon>
                </div>
              </div>
            </div>
          </div>
        </div>
      </el-scrollbar>
    </el-aside>

    <!-- 右侧好友详情 -->
    <el-main class="friend-detail">
      <!-- 未选择好友 -->
      <el-empty 
        v-if="!currentUser" 
        description="选择一个好友查看详情"
        :image-size="120"
      >
        <template #image>
          <el-icon :size="80" color="#409EFF"><User /></el-icon>
        </template>
      </el-empty>

      <!-- 好友详情 -->
      <div v-else class="detail-content">
        <!-- 头部信息 -->
        <el-card class="detail-header" shadow="never">
          <div class="header-content">
            <el-avatar :size="100" :src="'/images/face/' + currentUser.icon" class="detail-avatar">
              <img :src="'/images/face/' + currentUser.icon" />
            </el-avatar>
            
            <div class="header-info">
              <h2 class="user-nickname">{{ currentUser.nickname }}</h2>
              <el-text class="user-summary" type="info">
                {{ currentUser.summary || '这个人很懒，什么都没留下' }}
              </el-text>
              <div class="user-tags">
                <el-tag v-if="currentUser.robot" type="success" effect="plain">
                  <el-icon><Service /></el-icon>
                  智能助手
                </el-tag>
                <el-tag v-else type="primary" effect="plain">
                  <el-icon><User /></el-icon>
                  {{ currentUser.sex === 'male' ? '男' : currentUser.sex === 'female' ? '女' : '未知' }}
                </el-tag>
              </div>
            </div>
          </div>
        </el-card>

        <!-- 详细信息 -->
        <el-card class="detail-info" shadow="never">
          <template #header>
            <span>详细信息</span>
          </template>
          
          <el-descriptions :column="1" border>
            <el-descriptions-item label="微信号">
              <el-text>{{ currentUser.wxid }}</el-text>
              <el-button 
                :icon="CopyDocument" 
                size="small" 
                text 
                @click="copyToClipboard(currentUser.wxid)"
              />
            </el-descriptions-item>
            <el-descriptions-item label="地区">
              <el-text>{{ currentUser.area || '未设置' }}</el-text>
            </el-descriptions-item>
            <el-descriptions-item label="备注">
              <el-text>{{ currentUser.remark || '无' }}</el-text>
            </el-descriptions-item>
            <el-descriptions-item label="字母索引">
              <el-tag size="small">{{ currentUser.letter }}</el-tag>
            </el-descriptions-item>
          </el-descriptions>
        </el-card>

        <!-- 操作按钮 -->
        <el-card class="detail-actions" shadow="never">
          <div class="action-buttons">
            <el-button 
              type="primary" 
              :icon="ChatDotRound" 
              size="large"
              @click="sendMessage"
            >
              发消息
            </el-button>
            <el-button 
              :icon="VideoCamera" 
              size="large"
              @click="videoCall"
            >
              视频通话
            </el-button>
            <el-button 
              :icon="Phone" 
              size="large"
              @click="audioCall"
            >
              语音通话
            </el-button>
            <el-button 
              :icon="MoreFilled" 
              size="large"
              @click="showMoreActions"
            >
              更多
            </el-button>
          </div>
        </el-card>
      </div>
    </el-main>
  </el-container>
</template>

<script>
import http from '../utils/http'
import { ElMessage } from 'element-plus'
import {
  Search,
  UserFilled,
  User,
  Service, // 替换 Robot
  CopyDocument,
  ChatDotRound,
  VideoCamera,
  Phone,
  MoreFilled,
  CircleCheckFilled
} from '@element-plus/icons-vue'

export default {
  name: 'Friends',
  data() {
    return {
      searchValue: '',
      selectedUserId: 0,
      loading: true,
      // Element Plus 图标
      Search,
      UserFilled,
      User,
      Service, // 替换 Robot
      CopyDocument,
      ChatDotRound,
      VideoCamera,
      Phone,
      MoreFilled,
      CircleCheckFilled
    }
  },
  computed: {
    friends() {
      return this.state.friends || []
    },

    currentUser() {
      if (!this.friends.length) return null

      for (const group of this.friends) {
        const user = group.users.find(u => u.id === this.selectedUserId)
        if (user) return user
      }
      return null
    },

    filteredFriends() {
      if (!this.searchValue) return this.friends

      const keyword = this.searchValue.toLowerCase()
      return this.friends.map(group => ({
        ...group,
        users: group.users.filter(user =>
          user.nickname.toLowerCase().includes(keyword) ||
          user.wxid.toLowerCase().includes(keyword) ||
          (user.remark && user.remark.toLowerCase().includes(keyword))
        )
      })).filter(group => group.users.length > 0)
    }
  },
  async created() {
    await this.loadFriends()
    this.selectedUserId = this.friends[0]?.users[0]?.id || 0
  },
  methods: {
    // 加载好友列表
    async loadFriends() {
      try {
        this.loading = true
        console.log('开始加载好友列表...')
        const response = await http.get('/friends')
        
        if (response.data.success) {
          const friendsData = response.data.friends
          console.log('获取到好友数据:', friendsData)
          
          // 按字母分组好友
          const groupedFriends = this.groupFriendsByLetter(friendsData)
          
          // 更新全局状态
          this.state.friends = groupedFriends
          
          console.log('好友列表加载完成:', groupedFriends)
        } else {
          console.error('获取好友列表失败:', response.data.message)
          ElMessage.error('获取好友列表失败: ' + response.data.message)
        }
      } catch (error) {
        console.error('加载好友列表错误:', error)
        ElMessage.error('加载好友列表失败: ' + (error.response?.data?.message || error.message))
      } finally {
        this.loading = false
      }
    },

    // 按字母分组好友
    groupFriendsByLetter(friends) {
      const groups = {}
      
      friends.forEach(friend => {
        const letter = friend.letter || friend.nickname.charAt(0).toUpperCase()
        if (!groups[letter]) {
          groups[letter] = {
            letter: letter,
            users: []
          }
        }
        groups[letter].users.push(friend)
      })
      
      // 转换为数组并排序
      return Object.keys(groups)
        .sort()
        .map(letter => groups[letter])
    },
    
    handleClickUser(id) {
      this.selectedUserId = id
    },

    // 复制到剪贴板
    async copyToClipboard(text) {
      try {
        await navigator.clipboard.writeText(text)
        ElMessage.success('已复制到剪贴板')
      } catch (error) {
        ElMessage.error('复制失败')
      }
    },

    // 发送消息
    sendMessage() {
      if (!this.currentUser) {
        ElMessage.warning('请先选择一个好友')
        return
      }

      // 创建或查找与该好友的会话
      this.createOrFindConversation(this.currentUser)

      // 跳转到聊天页面
      this.$router.push('/chat')
      ElMessage.success(`开始与 ${this.currentUser.nickname} 聊天`)
    },

    // 创建或查找会话
    createOrFindConversation(friend) {
      // 检查是否已存在与该好友的会话
      let existingConversation = this.state.recents.find(recent =>
        recent.user.id === friend.id
      )

      if (!existingConversation) {
        // 创建新的会话
        const newConversation = {
          user: {
            id: friend.id,
            nickname: friend.nickname,
            icon: friend.icon,
            robot: friend.robot || 0
          },
          messages: []
        }

        // 添加到会话列表的开头
        this.state.recents.unshift(newConversation)

        // 保存到本地存储
        localStorage.setItem('recents' + this.state.user.id, JSON.stringify(this.state.recents))
      }

      // 设置当前选中的会话为第一个（刚创建或移动到顶部的）
      // 这样Chat页面就会显示与该好友的聊天
    },

    // 视频通话
    videoCall() {
      ElMessage.info('视频通话功能开发中...')
    },

    // 语音通话
    audioCall() {
      ElMessage.info('语音通话功能开发中...')
    },

    // 显示更多操作
    showMoreActions() {
      ElMessage.info('更多操作功能开发中...')
    },

    // 添加好友
    addFriend() {
      ElMessage.info('添加好友功能开发中...')
    }
  }
}
</script>

<style scoped>
/* 主容器 */
.friends-container {
  height: 100vh;
  background: var(--el-bg-color-page);
}

/* 左侧好友列表 */
.friends-sidebar {
  background: var(--el-bg-color);
  border-right: 1px solid var(--el-border-color-light);
}

.search-section {
  padding: 16px;
  border-bottom: 1px solid var(--el-border-color-lighter);
}

.friends-scrollbar {
  height: calc(100vh - 80px);
}

.loading-section {
  padding: 16px;
}

/* 好友分组 */
.friends-list {
  padding: 8px 0;
}

.friend-group {
  margin-bottom: 8px;
}

.group-header {
  padding: 8px 16px;
  background: var(--el-fill-color-lighter);
  border-bottom: 1px solid var(--el-border-color-extra-light);
}

.group-title {
  font-weight: 500;
  text-transform: uppercase;
}

.group-content {
  background: var(--el-bg-color);
}

/* 好友项 */
.friend-item {
  display: flex;
  align-items: center;
  padding: 12px 16px;
  cursor: pointer;
  transition: background-color 0.2s;
  border-bottom: 1px solid var(--el-border-color-extra-light);
}

.friend-item:hover {
  background: var(--el-fill-color-light);
}

.friend-item.active {
  background: var(--el-color-primary-light-9);
  border-right: 3px solid var(--el-color-primary);
}

.friend-avatar {
  margin-right: 12px;
  flex-shrink: 0;
}

.friend-info {
  flex: 1;
  min-width: 0;
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.friend-name {
  font-weight: 500;
}

.friend-summary {
  opacity: 0.8;
}

.friend-status {
  flex-shrink: 0;
  margin-left: 8px;
}

/* 右侧详情区域 */
.friend-detail {
  background: var(--el-bg-color-page);
  padding: 20px;
}

.detail-content {
  max-width: 600px;
  margin: 0 auto;
}

/* 头部信息卡片 */
.detail-header {
  margin-bottom: 20px;
}

.header-content {
  display: flex;
  align-items: center;
  gap: 20px;
}

.detail-avatar {
  flex-shrink: 0;
}

.header-info {
  flex: 1;
}

.user-nickname {
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 600;
  color: var(--el-text-color-primary);
}

.user-summary {
  display: block;
  margin-bottom: 12px;
  line-height: 1.4;
}

.user-tags {
  display: flex;
  gap: 8px;
}

/* 详细信息卡片 */
.detail-info {
  margin-bottom: 20px;
}

/* 操作按钮卡片 */
.detail-actions {
  margin-bottom: 20px;
}

.action-buttons {
  display: flex;
  gap: 12px;
  justify-content: center;
  flex-wrap: wrap;
}

.action-buttons .el-button {
  min-width: 120px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .friends-sidebar {
    position: absolute;
    left: -300px;
    top: 0;
    height: 100vh;
    z-index: 1000;
    transition: left 0.3s ease;
  }

  .friends-sidebar.mobile-show {
    left: 0;
  }

  .friend-detail {
    padding: 16px;
  }

  .header-content {
    flex-direction: column;
    text-align: center;
    gap: 16px;
  }

  .action-buttons {
    flex-direction: column;
  }

  .action-buttons .el-button {
    width: 100%;
  }
}

/* 自定义描述列表样式 */
:deep(.el-descriptions__body) {
  background: var(--el-bg-color);
}

:deep(.el-descriptions__label) {
  font-weight: 500;
  color: var(--el-text-color-regular);
}

:deep(.el-descriptions__content) {
  display: flex;
  align-items: center;
  gap: 8px;
}

/* 卡片标题样式 */
:deep(.el-card__header) {
  font-weight: 500;
  color: var(--el-text-color-primary);
}
</style>
